import mcpIcon from "@lobehub/icons-static-svg/icons/mcp.svg";
import { ButtonWithTooltip } from "@renderer/components/business/button-with-tooltip";
import { McpServerSelectModal } from "@renderer/components/business/mcp-server-select-modal";
import { ALLOWED_TYPES, MAX_FILE_COUNT } from "@renderer/hooks/use-attachments";
import { cn } from "@renderer/lib/utils";
import { useEnabledOrderedMcpServers } from "@renderer/queries/hooks/use-mcp-servers";
import { useChatToolbarSettings } from "@renderer/queries/hooks/use-settings";
import { Globe, Lightbulb, Paperclip } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { ChatParameters } from "./chat-parameters";

interface ActionGroupProps {
  onFilesSelect: (files: FileList) => void;
  disabled: boolean;
  selectedMcpServerIds: string[];
  onMcpServerSelectionChange: (serverIds: string[]) => void;
  attachmentCount: number;
}

const { settingsService } = window.service;

export function ActionGroup({
  onFilesSelect,
  disabled,
  selectedMcpServerIds,
  onMcpServerSelectionChange,
  attachmentCount,
}: ActionGroupProps) {
  const { t } = useTranslation();

  const { enableWebSearch, enableReason } = useChatToolbarSettings();
  const { data: mcpServers = [] } = useEnabledOrderedMcpServers();

  const [isMcpModalOpen, setIsMcpModalOpen] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);

  // Get selected servers info
  const selectedServers = useMemo(() => {
    return mcpServers.filter((server) =>
      selectedMcpServerIds.includes(server.id),
    );
  }, [mcpServers, selectedMcpServerIds]);

  const hasSelectedServers = selectedServers.length > 0;

  const mcpTooltipText = useMemo(() => {
    if (disabled) return t("chat.tool-bar.disabled");
    if (selectedServers.length === 0) {
      return t("chat.tool-bar.mcp-server-select-placeholder");
    }
    if (selectedServers.length === 1) {
      return selectedServers[0].name;
    }
    return t("chat.tool-bar.mcp-servers-selected", {
      count: selectedServers.length,
    });
  }, [disabled, selectedServers, t]);

  const handleAttachFile = () => {
    fileInputRef.current?.click();
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      onFilesSelect(files);
    }
    // Reset input value to allow selecting the same file again
    event.target.value = "";
  };

  const handleWebSearch = async () => {
    if (disabled) return;
    await settingsService.setEnableWebSearch(!enableWebSearch);
  };

  const handleReason = async () => {
    if (disabled) return;
    await settingsService.setEnableReason(!enableReason);
  };

  return (
    <div className="flex flex-row items-center gap-x-2">
      <ButtonWithTooltip
        title={`${t("chat.tool-bar.attach-file")} (${attachmentCount}/${MAX_FILE_COUNT})`}
        onClick={handleAttachFile}
      >
        <Paperclip className="size-4" />
      </ButtonWithTooltip>

      <ButtonWithTooltip
        className={cn(
          enableReason && "bg-primary/15 text-primary",
          disabled && "cursor-not-allowed opacity-50",
        )}
        title={
          disabled ? t("chat.tool-bar.disabled") : t("chat.tool-bar.thinking")
        }
        onClick={handleReason}
      >
        <Lightbulb className="size-4" />
      </ButtonWithTooltip>

      <ButtonWithTooltip
        className={cn(
          enableWebSearch && "bg-primary/15 text-primary",
          disabled && "cursor-not-allowed opacity-50",
        )}
        title={
          disabled
            ? t("chat.tool-bar.disabled")
            : t("chat.tool-bar.online-search")
        }
        onClick={handleWebSearch}
      >
        <Globe className="size-4" />
      </ButtonWithTooltip>

      {/* MCP Server Select Button */}
      {mcpServers.length > 0 && (
        <div className="relative">
          <ButtonWithTooltip
            className={cn(
              hasSelectedServers && "bg-primary/15 text-primary",
              disabled && "cursor-not-allowed opacity-50",
            )}
            title={mcpTooltipText}
            onClick={() => setIsMcpModalOpen(!isMcpModalOpen)}
            isDisabled={disabled}
          >
            <img
              src={mcpIcon}
              alt="MCP"
              className={cn(
                "size-4",
                hasSelectedServers
                  ? "[filter:brightness(0)_saturate(100%)_invert(24%)_sepia(84%)_saturate(4448%)_hue-rotate(270deg)_brightness(99%)_contrast(95%)]"
                  : "[filter:brightness(0)_saturate(100%)_invert(42%)_sepia(0%)_saturate(0%)_hue-rotate(0deg)_brightness(100%)_contrast(100%)] dark:[filter:brightness(0)_saturate(100%)_invert(58%)_sepia(0%)_saturate(0%)_hue-rotate(0deg)_brightness(100%)_contrast(100%)]",
              )}
            />
          </ButtonWithTooltip>

          <McpServerSelectModal
            isOpen={isMcpModalOpen}
            onOpenChange={setIsMcpModalOpen}
            selectedServerIds={selectedMcpServerIds}
            onSelectionChange={onMcpServerSelectionChange}
            mcpServers={mcpServers}
          />
        </div>
      )}

      <ChatParameters />

      <input
        ref={fileInputRef}
        type="file"
        className="hidden"
        multiple
        accept={ALLOWED_TYPES.join(",")}
        onChange={handleFileChange}
      />
    </div>
  );
}
